// frontend/static/js/app.js

let versionIndex = 0;
let results = [];

// ========= 生成令牌 =========
document.getElementById("genTokenBtn").onclick = async () => {
    try {
        const res = await fetch("/generate-token");
        const data = await res.json();
        if (data.token) {
            document.getElementById("token").value = data.token;
        } else {
            alert("生成失败");
        }
    } catch (err) {
        alert("失败：" + err.message);
    }
};

// ========= 上传并上链 =========
document.getElementById("uploadBtn").onclick = async () => {
    const config = document.getElementById("configInput").value;
    const deviceId = document.getElementById("deviceId").value;
    const operator = document.getElementById("operator").value;
    const token = document.getElementById("token").value;

    if (!config) {
        alert("请先输入配置内容！");
        return;
    }

    try {
        const res = await fetch("/upload-config", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "Authorization": `Bearer ${token}`
            },
            body: JSON.stringify({ config, device_id: deviceId, operator })
        });

        const data = await res.json();

        if (data.error) {
            alert("错误：" + data.error);
        } else {
            // ✅ 显示完整哈希
            document.getElementById("result").innerHTML =
                `<p><strong>上链成功！</strong> Block Hash: ${data.block.hash}</p>`;
        }
    } catch (err) {
        alert("请求失败：" + err.message);
    }
};

// ========= 加载区块链 =========
document.getElementById("loadChainBtn").onclick = async () => {
    const token = document.getElementById("token").value;
    const list = document.getElementById("chainList");
    list.innerHTML = "";

    try {
        const res = await fetch("/chain_latest", {
            headers: { "Authorization": `Bearer ${token}` }
        });

        if (res.status === 401) {
            alert("令牌无效或已过期");
            return;
        }

        const chain = await res.json();

        chain.forEach(block => {
            const item = document.createElement("div");
            item.className = "chain-item";
            item.innerHTML = `
                <strong>Block #${block.index}</strong> ${block.hash} |
                ${block.timestamp} | ${block.device_id} | ${block.config_preview}
            `;
            list.appendChild(item);
        });

    } catch (err) {
        alert("加载失败：" + err.message);
    }
};

// ========= 交互式对比 =========
document.getElementById("addVersionBtn").onclick = async () => {
    const config = document.getElementById("configInput").value;
    const deviceId = document.getElementById("deviceId").value;
    const operator = document.getElementById("operator").value;

    if (!config) {
        alert("请输入配置内容！");
        return;
    }

    try {
        const res = await fetch("/api/add-config", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ config, device_id: deviceId, operator })
        });

        const result = await res.json();

        if (result.error) {
            alert("错误：" + result.error);
            return;
        }

        versionIndex++;
        result.version = `V${versionIndex}`;
        results.push(result);

        const list = document.getElementById("compareList");
        const item = document.createElement("div");
        item.className = "compare-item";
        item.innerHTML = `
            <strong>${result.version}</strong> 全量: ${result.full_size} B, 差异: ${result.diff_size} B<br>
            <small>新增行: ${result.added_lines.join(', ')}</small>
        `;
        list.appendChild(item);

    } catch (err) {
        alert("请求失败：" + err.message);
    }
};

// ========= 生成图表 =========
document.getElementById("generateChartBtn").onclick = async () => {
    if (results.length === 0) {
        alert("请先添加至少一个版本！");
        return;
    }

    try {
        const res = await fetch("/api/generate-chart", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ results })
        });

        const data = await res.json();

        if (data.error) {
            alert("生成失败：" + data.error);
            return;
        }

        const pngLink = document.getElementById("pngLink");
        const csvLink = document.getElementById("csvLink");

        pngLink.href = data.png_url;
        pngLink.style.display = "block";

        csvLink.href = data.csv_url;
        csvLink.style.display = "block";

    } catch (err) {
        alert("生成失败：" + err.message);
    }
};